package com.me.app;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.DialogFragment;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.Toast;

import com.me.adapter.KArrayAdaptor;
import com.me.adapter.SArrayAdaptor;
import com.me.dialog.DatePickerFragment;
import com.me.dialog.TimePickerFragment;
import com.me.regex.AnalyseDate;
import com.me.regex.AnalyseLocation;
import com.me.regex.AnalyseTitle;
import com.me.util.AppConstant;
import com.me.util.AppUtil;
import com.me.util.GenNotification;

public class EventCreateActivity extends Activity implements OnClickListener,
		TimePickerFragment.OnTimePickedListener,
		DatePickerFragment.OnDatePickedListener, OnCheckedChangeListener {

	private ImageView ivCancel;
	private Button bStartDate, bStartTime, bEndDate, bEndTime, bSave, bCreate,
			bSugTitle, bSugVenue;
	private CheckBox cbAllDay;
	private AutoCompleteTextView etTitle, etVenue;
	private Calendar tempCal, startCal, endCal;
	private SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
	private SimpleDateFormat dateFormat = new SimpleDateFormat("d/M/yyyy");
	private SimpleDateFormat dateTimeFormat = new SimpleDateFormat(
			"d/M/yyyy HH:mm");
	private String inputTitle, inputVenue;
	private int inputAllDay;

	private SharedPreferences sharePrefs;
	private Boolean isSaved = false;
	private String eventIDForDelete;

	private ArrayList<String> suggestedTitle = new ArrayList<String>();
	private ArrayList<String> suggestedVenue = new ArrayList<String>();
	private ArrayList<String> historyTitle = new ArrayList<String>();
	private ArrayList<String> historyVenue = new ArrayList<String>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		// getWindow().setFlags(LayoutParams.FLAG_NOT_TOUCH_MODAL,
		// LayoutParams.FLAG_NOT_TOUCH_MODAL);
		// getWindow().setFlags(LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
		// LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH);

		setContentView(R.layout.activity_event_create);

		// Set up the default start end date time
		startCal = Calendar.getInstance();
		startCal.add(Calendar.HOUR_OF_DAY, 1);
		startCal.set(Calendar.MINUTE, 0);
		endCal = Calendar.getInstance();
		endCal.add(Calendar.HOUR_OF_DAY, 2);
		endCal.set(Calendar.MINUTE, 0);

		// suggestedTitle.add("Title : Interview");
		// suggestedTitle
		// .add("Venue : Unit 1106-08 , Cyberport 2 , 100 Cyberport Road , Pokfulam , Hong Kong");
		//
		// suggestedVenue
		// .add("Unit 1106-08 , Cyberport 2 , 100 Cyberport Road , Pokfulam , Hong Kong");
		// suggestedVenue.add("Unit 1106-08");
		// suggestedVenue
		// .add("Cyberport 2 , 100 Cyberport Road , Pokfulam , Hong Kong");
		//
		// historyTitle = AppUtil.App.dataService.getAllTitles();
		// historyVenue = AppUtil.App.dataService.getAllLocation();

		bindingComponents();
		addAdapterToViews();
		Intent i = getIntent();
		readData(i);
		updateButtonDateTime();

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		// If we've received a touch notification that the user has touched
		// outside the app, finish the activity.
		if (MotionEvent.ACTION_OUTSIDE == event.getAction()) {
			moveTaskToBack(true);
			return false;
		}
		// Delegate everything else to Activity.
		return super.onTouchEvent(event);
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.ivCancel:
			finish();
			break;
		case R.id.bStartDate:
			DialogFragment startDatePicker = DatePickerFragment.newInstance(1,
					startCal.get(Calendar.YEAR), startCal.get(Calendar.MONTH),
					startCal.get(Calendar.DAY_OF_MONTH));

			System.out.println(startCal.get(Calendar.MONTH) + " "
					+ startCal.get(Calendar.DAY_OF_MONTH));

			startDatePicker.show(getFragmentManager(), "datePicker");
			break;
		case R.id.bStartTime:
			DialogFragment startTimePicker = TimePickerFragment.newInstance(1,
					startCal.get(Calendar.HOUR_OF_DAY),
					startCal.get(Calendar.MINUTE));
			startTimePicker.show(getFragmentManager(), "timePicker");
			break;
		case R.id.bEndDate:
			DialogFragment endDatePicker = DatePickerFragment.newInstance(2,
					endCal.get(Calendar.YEAR), endCal.get(Calendar.MONTH),
					endCal.get(Calendar.DAY_OF_MONTH));
			endDatePicker.show(getFragmentManager(), "datePicker");
			break;
		case R.id.bEndTime:
			DialogFragment endTimePicker = TimePickerFragment.newInstance(2,
					endCal.get(Calendar.HOUR_OF_DAY),
					endCal.get(Calendar.MINUTE));
			endTimePicker.show(getFragmentManager(), "timePicker");
			break;
		case R.id.bSave:

			cleanData();
			// etTitle = (AutoCompleteTextView) findViewById(R.id.etTitle);
			inputTitle = etTitle.getText().toString();
			// etVenue = (AutoCompleteTextView) findViewById(R.id.etLocation);
			inputVenue = etVenue.getText().toString();
			inputAllDay = (cbAllDay.isChecked()) ? 1 : 0;

			if (inputTitle != null && inputTitle.length() > 0) {
				if (eventIDForDelete == null) { // insert new pending event
					AppUtil.App.dataService.insertOneEvent(inputTitle,
							inputVenue, inputAllDay,
							startCal.getTimeInMillis(),
							endCal.getTimeInMillis());
				} else { // update old pending event
					AppUtil.App.dataService.updateEvent(eventIDForDelete,
							inputTitle, inputVenue, inputAllDay,
							startCal.getTimeInMillis(),
							endCal.getTimeInMillis());
				}
				GenNotification.show(getPackageName(), this);
				AppUtil.Event.dataChanged = true;
				finish();
			}
			break;
		case R.id.bCreate:

			cleanData();
			// etTitle = (AutoCompleteTextView) findViewById(R.id.etTitle);
			inputTitle = etTitle.getText().toString();
			// etVenue = (AutoCompleteTextView) findViewById(R.id.etLocation);
			inputVenue = etVenue.getText().toString();
			inputAllDay = (cbAllDay.isChecked()) ? 1 : 0;

			if (inputTitle != null && inputTitle.length() > 0) {

				AppUtil.App.dataService.insertOneCalendarEvent(inputTitle,
						inputVenue, inputAllDay, startCal.getTimeInMillis(),
						endCal.getTimeInMillis());

				if (eventIDForDelete != null) { // delete old pending event
												// after it moved to calendar
					AppUtil.App.dataService.deleteEvents(
							AppConstant.EVENT_INDEX_PENDING,
							new String[] { eventIDForDelete });
				}
				GenNotification.show(getPackageName(), this);

				AppUtil.Event.dataChanged = true;
				finish();
			}
			break;
		case R.id.bSugTitle:
			addAdapterToViews();
			etTitle.showDropDown();
			break;
		case R.id.bSugVenue:
			addAdapterToViews();
			etVenue.showDropDown();
			break;
		}
	}

	// Initial setup of the components
	public void bindingComponents() {
		// Initialize the components
		ivCancel = (ImageView) findViewById(R.id.ivCancel);
		bStartDate = (Button) findViewById(R.id.bStartDate);
		bStartTime = (Button) findViewById(R.id.bStartTime);
		bEndDate = (Button) findViewById(R.id.bEndDate);
		bEndTime = (Button) findViewById(R.id.bEndTime);
		bSave = (Button) findViewById(R.id.bSave);
		bCreate = (Button) findViewById(R.id.bCreate);
		bSugTitle = (Button) findViewById(R.id.bSugTitle);
		bSugVenue = (Button) findViewById(R.id.bSugVenue);
		cbAllDay = (CheckBox) findViewById(R.id.cbAllDay);
		etTitle = (AutoCompleteTextView) findViewById(R.id.etTitle);
		etVenue = (AutoCompleteTextView) findViewById(R.id.etLocation);

		// Set up the corresponding listener
		ivCancel.setOnClickListener(this);
		bStartDate.setOnClickListener(this);
		bStartTime.setOnClickListener(this);
		bEndDate.setOnClickListener(this);
		bEndTime.setOnClickListener(this);
		bSave.setOnClickListener(this);
		bCreate.setOnClickListener(this);
		bSugTitle.setOnClickListener(this);
		bSugVenue.setOnClickListener(this);
		cbAllDay.setOnCheckedChangeListener(this);

		etTitle.addTextChangedListener(new TextWatcher() {

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {

			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {

				if (etTitle.getText().toString().isEmpty()) {
					System.out.println("HIHI");
					etTitle.setAdapter(new ArrayAdapter<String>(
							getBaseContext(), R.layout.suggestion_item,
							historyTitle));
					etVenue.setAdapter(new ArrayAdapter<String>(
							getBaseContext(), R.layout.suggestion_item,
							historyVenue));
					etTitle.setThreshold(2);
					etVenue.setThreshold(2);
				}

			}

		});

		setFinishOnTouchOutside(true);
	}

	public void updateButtonDateTime() {
		bStartTime.setText(timeFormat.format(startCal.getTime()));
		bEndTime.setText(timeFormat.format(endCal.getTime()));
		bStartDate.setText(dateFormat.format(startCal.getTime()));
		bEndDate.setText(dateFormat.format(endCal.getTime()));
	}

	public void onTimePicked(int pickerId, int hourOfDay, int minute) {
		System.out.println(hourOfDay + "  " + minute);
		switch (pickerId) {
		case 1:
			tempCal = (Calendar) startCal.clone();
			int hourDiff = endCal.get(Calendar.HOUR_OF_DAY)
					- tempCal.get(Calendar.HOUR_OF_DAY);
			startCal.set(Calendar.HOUR_OF_DAY, hourOfDay);
			startCal.set(Calendar.MINUTE, minute);

			if (startCal.after(endCal)) {
				endCal = (Calendar) startCal.clone();
				endCal.add(Calendar.HOUR_OF_DAY, hourDiff);
			}
			updateButtonDateTime();
			break;
		case 2:
			tempCal = (Calendar) endCal.clone();
			endCal.set(Calendar.HOUR_OF_DAY, hourOfDay);
			endCal.set(Calendar.MINUTE, minute);
			if (startCal.after(endCal)) {
				Toast.makeText(this,
						"End Date should be later than Start Date!",
						Toast.LENGTH_SHORT).show();
				endCal = (Calendar) tempCal.clone();
			} else {
				updateButtonDateTime();
			}

			break;
		}
	}

	@Override
	public void onDatePicked(int pickerId, int year, int month, int day) {

		switch (pickerId) {
		case 1:
			startCal.set(Calendar.YEAR, year);
			startCal.set(Calendar.MONTH, month);
			startCal.set(Calendar.DAY_OF_MONTH, day);
			if (startCal.after(endCal)) {
				endCal = (Calendar) startCal.clone();
				endCal.add(Calendar.HOUR_OF_DAY, 1);
			}
			updateButtonDateTime();
			break;
		case 2:
			tempCal = (Calendar) endCal.clone();
			endCal.set(Calendar.YEAR, year);
			endCal.set(Calendar.MONTH, month);
			endCal.set(Calendar.DAY_OF_MONTH, day);
			if (startCal.after(endCal)) {
				Toast.makeText(this,
						"End Date should be later than Start Date!",
						Toast.LENGTH_SHORT).show();
				endCal = (Calendar) tempCal.clone();
			} else {
				updateButtonDateTime();
			}
			break;
		}
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

		if (buttonView.isChecked()) {
			bStartTime.setVisibility(View.GONE);
			bEndTime.setVisibility(View.GONE);
		} else {
			bStartTime.setVisibility(View.VISIBLE);
			bEndTime.setVisibility(View.VISIBLE);
		}
	}

	// Create the suggestion drop doen list view
	private void addAdapterToViews() {
		// Country AutoCompleteTextView
		// etTitle.setAdapter(new SArrayAdaptor(this, R.layout.suggestion_item,
		// historyTitle, suggestedTitle));
		// etVenue.setAdapter(new SArrayAdaptor(this, R.layout.suggestion_item,
		// historyVenue, suggestedVenue));
		// etTitle.setThreshold(2);
		// etVenue.setThreshold(2);
		etTitle.setAdapter(new KArrayAdaptor<String>(this,
				R.layout.suggestion_item, suggestedTitle));
		etVenue.setAdapter(new KArrayAdaptor<String>(this,
				R.layout.suggestion_item, suggestedVenue));
		etTitle.setThreshold(999);
		etVenue.setThreshold(999);
		if (suggestedTitle.size() == 0)
			bSugTitle.setVisibility(View.GONE);
		if (suggestedVenue.size() == 0)
			bSugVenue.setVisibility(View.GONE);

		// etTitle.setAdapter(new ArrayAdapter<String>(this,
		// R.layout.suggestion_item, historyTitle));
		// etVenue.setAdapter(new ArrayAdapter<String>(this,
		// R.layout.suggestion_item, historyVenue));
		//

	}

	public String copyFromClipboard() {

		ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
		String clipText = null;

		ClipData clipData = clipboard.getPrimaryClip();
		if (clipData != null) {
			ClipData.Item clipItem = clipData.getItemAt(0);
			clipText = clipItem.getText().toString();
		}

		return clipText;

	}

	// Read the editing event data
	public void readData(Intent i) {

		// Get data when editing a pending event
		if (i.getBooleanExtra("IsEdit", false)) {
			etTitle.setText(i.getStringExtra("Title"));
			etVenue.setText(i.getStringExtra("Venue"));
			startCal = (Calendar) i.getSerializableExtra("StartCal");
			endCal = (Calendar) i.getSerializableExtra("EndCal");
			cbAllDay.setChecked(i.getBooleanExtra("IsAllDay", false));
			eventIDForDelete = i.getStringExtra("EventID");

		}
		// Get temporary stored event data when creating new event
		else {

			sharePrefs = getSharedPreferences("Event", 0);
			etTitle.setText(sharePrefs.getString("Title", ""));
			etVenue.setText(sharePrefs.getString("Venue", ""));
			try {
				startCal.setTime(dateTimeFormat.parse(sharePrefs.getString(
						"Start", "")));
				endCal.setTime(dateTimeFormat.parse(sharePrefs.getString("End",
						"")));
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			// String input = copyFromClipboard();
			// if (input != null) {
			// String title = AnalyseTitle.analyse(input).get(0);
			// etTitle.setText(title);
			// String venue = AnalyseLocation.analyse(input).get(0);
			// etVenue.setText(venue);
			//
			// ArrayList<Date> dates = AnalyseDate.analyse(input);
			// if (dates.size() > 0) {
			// Date date1 = dates.get(0);
			// Date date2 = (dates.size() > 1)? dates.get(1): dates.get(0);
			//
			// if (date1.getTime() > date2.getTime()) {//reverse
			// Date temp = date1;
			// date1 = date2;
			// date2 = temp;
			// }
			//
			// startCal.setTime(date1);
			// endCal.setTime(date2);
			//
			// }
			//
			// }
		}

	}

	// Clean the temporary event data when it is used
	public void cleanData() {

		isSaved = true;
		sharePrefs = getSharedPreferences("Event", 0);
		sharePrefs.edit().putString("Title", "").putString("Venue", "")
				.putString("Start", "").putString("End", "").commit();

	}

	// When the activity stops, save the temporary event data only when the
	// creating event is not saved.
	@Override
	protected void onStop() {
		super.onStop();

		if (!isSaved && eventIDForDelete == null) {
			sharePrefs = getSharedPreferences("Event", 0);
			sharePrefs
					.edit()
					.putString("Title", etTitle.getText().toString())
					.putString("Venue", etVenue.getText().toString())
					.putString("Start",
							dateTimeFormat.format(startCal.getTime()))

					.putString("End", dateTimeFormat.format(endCal.getTime()))
					.commit();

		}
	}

}
